import { MessagePlugin } from "tdesign-vue-next";
import type { NitroFetchRequest } from 'nitropack';
import type { FetchOptions } from 'ofetch';
import { useLoading } from "~/store/manager/loading";

let baseUrl = 'http://api.center.ios/index.php/api/v1';

interface Params {
    url: NitroFetchRequest;
    opts: FetchOptions<any>;
    method?: 'get' | 'post'
}




export function Http({ url, opts, method = 'get' }: Params): Promise<void> {
    console.log('开始执行HTTP');
    const loadingStore = useLoading();
    loadingStore.setTableLoading(true);
    const data = new Promise<void>(async (resolve, reject) => {
        console.log('开始执行promise');
        await nextTick();
        useFetch(baseUrl + url, {
            method: method,
            onRequest({ request, options }) {
                // 获取请求头信息
                const tokenInfo: any = localStorage.getItem('token');
                let token: any = ''
                if (tokenInfo != null || tokenInfo != undefined) {
                    // 本地存在token信息，格式化token
                    token = JSON.parse(tokenInfo);
                    token = token.token_type + ' ' + token.access_token
                }
                // 设置请求头
                options.headers = { ...options.headers, Authorization: token };
                // 设置请求参数
                if (method === 'post') {
                    options.body = { ...opts };
                }
            },
            onResponse({ response }) {
                // console.log(response._data);
                // 相应状态码判断
                if (response.status === 500) {
                    MessagePlugin.error({
                        content: '服务器端出现了500错误~~:('
                    })

                    // 隐藏loading
                    loadingStore.setTableLoading(false);

                    return;
                }
                if (response.status === 401) {
                    console.log(401);
                    const router = useRouter();
                    router.replace('/user/login')
                }
                // 服务器返回状态判断
                // 服务器返回false
                if (!(response._data.success)) {
                    MessagePlugin.error({
                        content: response._data.message
                    });
                    // 隐藏loading
                    loadingStore.setTableLoading(false);
                    return;
                }

                // 隐藏loading
                loadingStore.setTableLoading(false);

                // 服务器返回true
                resolve(response._data)

            },
            onRequestError({ request, options, error }) {
                console.log('err-request');
                reject(error);

            },
            onResponseError({ request, response, options }) {
                console.log('err-response');
                reject(response)
            }
        })
    })
    return data;
};


// GET请求
export async function get(url: string, opts: any = {}) {
    console.log('开始执行get请求...');

    return await Http({ url, opts, method: 'get' });
}

// POST请求
export async function post(url: string, opts: any = {}) {
    return await Http({ url, opts, method: 'post' })
}